#html解析器
from bs4 import BeautifulSoup
import re
from urllib.parse import urljoin
class HtmlDParser(object):
    def parse_(self,page_url,html_cont):
        if page_url is None or html_cont is None:
            return None
        soup = BeautifulSoup(html_cont,'html.parser',from_encoding='utf-8')
        news_urls = self._get_news_urls(page_url,soup)#解析出url
        news_data = self._get_news_data(page_url,soup)#解析出内容
        return news_urls,news_data

    def _get_news_urls(self,page_url,soup):
        new_urls=set()
        #http://baike.baidu.com/item/Python
        links = soup.find_all('a',href=re.compile(r"/item/.*"))
        for link in links:
            new_url = link['href']
            news_full_url = urljoin(page_url,new_url)
            new_urls.add(news_full_url)
        return new_urls

    def _get_news_data(self,page_url,soup):
        res_data={}
        res_data['url'] = page_url
        #标题  <dd class="lemmaWgt-lemmaTitle-title"><h1>Python</h1>
        title_node = soup.find('dd',class_='lemmaWgt-lemmaTitle-title').find('h1')
        res_data['title']=title_node.get_text()

        #简介 <div class="lemma-summary" label-module="lemmaSummary">
        summary_node = soup.find('div',class_='lemma-summary')
        res_data['summary'] = summary_node.get_text()
        return res_data